<?php
namespace control;
/*
*标签类
*/


class tagClass extends adIndexClass
{
    private const title = '标签';
    private const page = 'tag';
    private const table = 'tag';

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('tag.home.name') => text(array("name" => "name")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{id:'" . suiji() . "'})\" class='spanButton'>".L('tag.home.new')."</span>\n ";

        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('tag.home.del')."</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),//标签
        );
        //全等查询数组
        $equal = array(
            'coid'=>self::$coid
        );

        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal))." and type=0";
        $page = $this->page(array("table" => self::table, "where" => $where, 'pageNum' => 5, "order" => "time desc"));
        //获取表头
        //获取记录
        $html = "<ul class='tag-list-ul'>";
        $root = root;
        foreach ($page['array'] as $array) {
            $creatName = self::findStaff($array['stid']);
            $detail_html = '';
            $mxResult = find(array('table'=>self::table.'_detail','where'=>"orderId = '$array[id]' order by list asc"));
            foreach ($mxResult['array'] as $val){
                $detail_html.=<<<eee
<li class="background-color-gray">{$val['name']}</li> 
eee;
            }

            $html .= <<<efo
<li>
     <div class="tag-contain">
           <div class="tag-contain-title">
                 <input name="listId[]" type="checkbox" value="$array[id]">
                 <span class="tag-contain-title-text">{$array['name']}</span>
           </div>
           <div class="tag-contain-body">
                 <ul class="tag-contain-ul">
                     {$detail_html}
                 </ul>
           </div>
           <div class="tag-contain-foot">
                <span>{$creatName}</span>
                <span>{$array['time']}</span>
           </div>
           <div class="tag-edit-content">
                <img alt="" onclick="layer('tag','operate',{act:'del',id:'{$array['id']}'})" src="{$root}img/control/delete.svg">
                <img onclick="layer('tag','edit',{id:'{$array['id']}'})" alt="" src="{$root}img/control/edit.svg">
           </div>
     </div>
</li>
efo;

        }
        $html .= <<<efo
</ul>
<style>
.tag-list-ul{display: inline-flex}
.tag-list-ul>li{float: left;margin: 0 10px 10px 0;}
.tag-contain{width: 300px;height: 400px;padding: 10px;border: 1px solid #d7d7d7;border-radius: 2px}
.tag-contain-title-text{margin-left: 10px;font-weight: bold;font-size: 14px}
.tag-contain-body{margin: 10px;padding: 10px;height: 250px;overflow: auto}
.tag-contain-ul li{float: left;margin: 10px 5px}
.tag-contain-foot{margin: 10px;padding: 10px;border-bottom: 1px solid #d7d7d7}
.tag-contain-foot span:nth-child(2){float: right}
.tag-edit-content{text-align: right}
.tag-edit-content img:nth-child(2){width: 20px;cursor: pointer}
.tag-edit-content img:nth-child(1){width: 22px;cursor: pointer}
}
</style>
<script>
//展示输入框
function showInput(e){
    let id = $(e).parent().parent().parent().parent().find("input[name='attrId[]']").val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=showInput',{id:id},function (res){
        $(e).parent().before(res.html);
        $(e).css('display','none');
    },'json')
}
//展示添加按钮
function showAddButton(e){
    let val = e.value;
    let id = $(e).parent().parent().parent().parent().find("input[name='attrId[]']").val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=showAddButton',{id:id,val:val},function (res){
        $(e).parent().after(res.html);
        $(e).parent().remove();
        $(".add-attr-button").css('display','inline-flex');
    },'json')
}
function del_this(e){
    $(e).parent().remove();
}
</script>
efo;

        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $html . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 显示输入框
     */
    public function showInput(): bool|string
    {
        $json['html'] = <<<efo
<li><input name="label_name[]" type="text" onblur="showAddButton(this)" value=""></li>
efo;
        return json_encode($json, 320);
    }

    /**
     * 显示添加按钮
     * @return bool|string
     */
    public function showAddButton(): bool|string
    {
        $val = $this->post('val');//值
        $json['html'] = '';
        if (!empty($val)) {
            $mxId = self::getId();
            $json['html'] = <<<efo
<li><span class='background-color-gray li-ico'>{$val}<input name='labelId[]' type='hidden' value='{$mxId}'><input name='label_name[]' type='hidden' value='{$val}'></span><a onclick='del_this(this)'><div><span class='u-icon-delete'><i></i></span></div></a></li>
efo;
        }
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        $mxResult = find(array('table' => self::table . '_detail', 'where' => "orderId = '$info[id]'"));
        $label = "<ul class='label-edit-ul addAttr'>";
        foreach ($mxResult['array'] as $val) {
            $label .= "<li><span class='background-color-gray li-ico'>{$val['name']}<input name='labelId[]' type='hidden' value='{$val['id']}'><input name='label_name[]' type='hidden' value='{$val['name']}'></span><a onclick='del_this(this)' href='javascript:void(0)'><div><span class='u-icon-delete'><i></i></span></div></a></li>";
        }
        $label .= "<li><div class='add-attr-button' onclick=\"showInput(this)\">+</div></li></ul>";
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('tag.edit.name')."：" => text(array("name" => "name", "class" => "text", "value" => $info['name'])),
            ),
            array(
                must . L('tag.edit.tag')."：" => $label,
            ),
        )));


        return $this->layer(array("title" => L('tag.edit.edit'), "height" => 250, "width" => 800, "html" => $html));
    }


    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $label_name = $this->post('label_name');
        $label_id = $this->post('labelId');
        $field = [
            "name" => $this->post('name'),//联系人姓名
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        ];
        $annotation = [
            'name' => L('tag.edit.name'),
        ];
        $rules = [
            'name' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('tag.editEdit.power');
        }elseif(empty($label_id) || !is_array($label_id)){
            $json['warn'] = L('tag.editEdit.noChoice');
        } elseif (static::total(array('table' => self::table, 'where' => "name = '$field[name]' and type=0 and id !='$id'")) > 0) {
            $json['warn'] = L('tag.editEdit.repeat');
        }else {
            $isPass = true;
            $this->startTrans();
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'type'=>0,
                    'coid'=>self::$coid,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "where" => $where,
                    "field" => $field,
                ]);
            }
            foreach ($label_id as $k=>$mxId){
                $mx = query(self::table.'_detail',"id = '$mxId'");
                if (empty($mx['id'])){
                   $warn = static::insert(["table" => self::table.'_detail', "field" => [
                        'id'=>$mxId,
                        'coid'=>self::$coid,
                        'orderId'=>$id,
                        'name'=>$label_name[$k],
                    ]]);
                   if ($warn !='新增成功'){
                       $json['warn'] = $warn;
                       $isPass = false;
                       break;
                   }
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(array('table'=>self::table.'_detail','where'=>"id not in ('".implode("','",$label_id)."') and orderId = '$id'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('tag.editEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }else{
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('tag.operate.del');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('tag.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('tag.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('tag.delete.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if (static::total(array('table'=>'kehu_label','where'=>"tagId = '$id'"))) {
                    //返回
                    $warn = L('tag.delete.fail');
                } else {
                    delete(array("table" => self::table.'_detail', "where" => " orderId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = L('tag.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], L('tag.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('tag.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('tag.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }


}
